#include "pch.h"
#include "FileTransferImpl.h"
#include "FileIOManager.h"
#include "FileReadTask.h"
#include "..\Common\SRWLock.h"

CFileTransfer::CFileTransfer()
	: m_nLastTaskId(0)
{
}

CFileTransfer::~CFileTransfer()
{
	assert(!m_pFileIOManager);
}

bool CFileTransfer::Init()
{
	AssertInUIThread();
	assert(!m_pFileIOManager);

	CExclusiveLock lock(m_SRWLock);
	m_pFileIOManager = std::make_unique<CFileIOManager>();
	return m_pFileIOManager->Init();
}

void CFileTransfer::Exit()
{
	AssertInUIThread();

	CExclusiveLock lock(m_SRWLock);
	auto pFileIOManager = std::move(m_pFileIOManager);
	lock.Unlock();

	if (pFileIOManager)
		pFileIOManager->Exit();
}

bool CFileTransfer::ReadFile(LPCWSTR lpFileName, IFileReaderPtr pCallback, INT64 nOffset, INT64 nLength)
{
	AssertInThreadpool();

	if (!lpFileName || !pCallback)
		return false;

	auto pTask = std::make_shared<CFileReadTask>(lpFileName, std::move(pCallback), nOffset, nLength);
	AddAndRunTask(pTask);
	return true;
}

void CFileTransfer::AddAndRunTask(const std::shared_ptr<CFileIOTask>& pTask)
{
	CSharedLock lock(m_SRWLock);

	if (m_pFileIOManager)
	{
		pTask->SetId(++m_nLastTaskId);
		m_pFileIOManager->AddAndRunTask(pTask);
	}
}
